package com.easy.reconciliation.controller;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.easy.reconciliation.entity.ServiceInfo;
import com.easy.reconciliation.service.Servers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

/**
 * @Packge com.easy.reconciliation.controller
 * @Autor linNaibin
 * @Description 模仿分布式中的 leader ， 用于接收请求，分发请求 ；
 * @Version 1.0
 * @Date 2021/11/18 11:42
 */
@RestController
public class LeaderController {

    private static final Logger logger = LoggerFactory.getLogger(LeaderController.class);

    private Servers servers;

    @Autowired
    public LeaderController(Servers servers) {
        this.servers = servers;
    }


    @GetMapping("/heartbeat")
    public JSONObject heartbeat() {
        return null;
    }

    @RequestMapping("/execute")
    public JSONObject execute() {
        logger.info("开始执行execute方法...");

        //
        Random random = new Random();

        int count = random.nextInt(360000) + 40000;

        logger.info("需要处理的数据有{}条.", count);

        // 根据缓存信息，拿到 服务
        List<ServiceInfo> onlineServer = servers.getServices();

        int record = count / onlineServer.size();
        for (int i = 0; i < onlineServer.size(); i++) {
            ServiceInfo s = onlineServer.get(i);
            int tmp;
            if (i != onlineServer.size() - 1) {
                tmp = record;
            } else {
                tmp = count - (record * (i));
            }
            s.setData(tmp);
            logger.info("服务器{},需要处理{}条数据.", s.getName(), s.getData());

        }

        //
        logger.info("leader 开始分发任务..");
        onlineServer.stream().forEach(s -> {
            HttpUtil.get(s.getAddress() + s.getExecute());
        });

        logger.info("任务处理完毕..");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("server", onlineServer);
        jsonObject.put("total", count);

        return jsonObject;
    }

}
